'use client';

import React, { useEffect, useMemo, useState } from 'react';

import { Viewer } from '@bytemd/react';

import { plugins, sanitize } from './config';

type BytemdViewerProps = {
    body: string;
};

export const BytemdViewer = ({ body }: BytemdViewerProps) => {
    const [isClient, setIsClient] = useState(false);

    useEffect(() => {
        setIsClient(true);
    }, []);

    const memoizedViewer = useMemo(() => {
        if (!isClient) {
            return (
                <div className="bytemd-loading">
                    <div className="loading-spinner"></div>
                    <span className="loading-text">加载中...</span>
                </div>
            );
        }
        return (
            <div className="markdown-body">
                <Viewer value={body} plugins={plugins} sanitize={sanitize} />
            </div>
        );
    }, [body, isClient]);

    return memoizedViewer;
};
